package com.cust.zy.newtask.dao;


import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import com.cust.zy.newtask.TaskApplication;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;


/**
 * Created by zhuangyuan on 4/15/2017.
 * 邮箱：zhuangyuan.k@qq.com
 */
public class DBOpenHelper extends SQLiteOpenHelper {

    public DBOpenHelper(Context context) {
        super(context, TaskApplication.DB_NAME, null, 1);
    }

    private static DBOpenHelper mInstance;

    public synchronized static DBOpenHelper getInstance(Context context) {
        if (mInstance == null) {
            mInstance = new DBOpenHelper(context);
        }
        return mInstance;
    };
    //第一次创建数据库时执行
    @Override
    public void onCreate(SQLiteDatabase db) {
        String taskSql = "CREATE TABLE Task ( ID text PRIMARY KEY, NAME text not null , NUM_OF_WORD integer , " +
                "GENERATE_TIME text not null, DESCRIPTION text , TYPE integer not null);";
        String wordSql = "CREATE TABLE Word ( ID text PRIMARY KEY, NAME text not null , TRANSLATION text not null, " +
                "PHONETIC_ALPHABET text, LIST text not null,TASK_ID text not null);";
        String wordNoteSql = "CREATE TABLE WordNote (NAME text PRIMARY KEY, ID text not null);";
        String scheduleSql = "CREATE TABLE Schedule ( ID text not null, am text not null , pm text not null);";
        try {
            db.execSQL(taskSql);
            db.execSQL(wordNoteSql);
            db.execSQL(wordSql);
            db.execSQL(scheduleSql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //版本号更改时执行
    @Override
    public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {

        Log.i("testUpgrade", "Upgrade");
    }
    public static byte[] objectToBytes(Object obj) throws Exception {

        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ObjectOutputStream sOut = new ObjectOutputStream(out);
        sOut.writeObject(obj);
        sOut.flush();
        byte[] bytes = out.toByteArray();
        return bytes;
    }

    public static Object bytesToObject(byte[] bytes) throws Exception {

        ByteArrayInputStream in = new ByteArrayInputStream(bytes);
        ObjectInputStream sIn = new ObjectInputStream(in);
        return sIn.readObject();
    }
}
